package com.iweipan.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.iweipan.R;
import com.iweipan.activity.LoginActivity;
import com.iweipan.activity.RegisterActivity;
import com.iweipan.activity.WebViewActivity;
import com.iweipan.base.WPBaseFragment;
import com.iweipan.base.WPUrlBase;
import com.iweipan.bean.TodayKLineBean;
import com.iweipan.utils.sputils.SPUtils;
import com.iweipan.view.MyViewPager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.iweipan.R.id.buy_layout;
import static com.iweipan.base.WPUrlBase.WP_USER_BALANCES;
import static com.iweipan.base.WPUrlBase.WP_USER_CLOSEORDER;
import static com.iweipan.base.WPUrlBase.WP_USER_COUNTS;
import static com.iweipan.base.WPUrlBase.WP_USER_MYBUYLIST;

;

/**
 * Created by Administrator on 2016/11/17.
 */

public class InforMationFragment extends WPBaseFragment implements KLineFragment.OnValueSelected {


    @BindView(R.id.nowPrice)
    TextView nowPrice;
    @BindView(R.id.center_view)
    View centerView;
    @BindView(R.id.maxText)
    TextView maxText;
    @BindView(R.id.afterText)
    TextView afterText;
    @BindView(R.id.minText)
    TextView minText;
    @BindView(R.id.todayText)
    TextView todayText;
    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.vp_view)
    MyViewPager vpView;
    @BindView(R.id.buy_up)
    Button buyUp;
    @BindView(R.id.buy_low)
    Button buyLow;
    @BindView(buy_layout)
    LinearLayout buyLayout;
    @BindView(R.id.login_btn)
    Button loginBtn;
    @BindView(R.id.register_btn)
    Button registerBtn;
    @BindView(R.id.login_layout)
    LinearLayout loginLayout;
    @BindView(R.id.my_money)
    TextView myMoney;
    @BindView(R.id.my_quan)
    TextView myQuan;
    @BindView(R.id.ping_btn)
    Button pingBtn;
    @BindView(R.id.ping_layout)
    LinearLayout pingLayout;
    @BindView(R.id.jiancang)
    TextView jiancang;
    @BindView(R.id.baoben)
    TextView baoben;
    @BindView(R.id.yingkui)
    TextView yingkui;
    @BindView(R.id.weight)
    TextView weight;

    private AlertDialog.Builder builder;
    private boolean isFirst = true;
    private Handler handler;
    private boolean isEnd = true; // 滑动查看是否完成  true  完成 false 没有完成
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private List<Fragment> mViewList = new ArrayList<>();//页卡视图集合
    private boolean isLogin = false;
    private boolean isBuy = false;
    private String wp_token = "";
    private int addNum;
    private AlertDialog alertDialog;
    private MyBundle integerHashMap = new MyBundle();
    private int orderId = 0;
    private int buyDirection;
    private int count;
    private double plRatio;
    private int buyPrice;
    private int couponFlag;
    private RefreshMoney refreshMoney;
    private int redColor;
    private int greenColor;

    public static InforMationFragment newInstance() {

        Bundle args = new Bundle();
        InforMationFragment fragment = new InforMationFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        refreshMoney = (InforMationFragment.RefreshMoney) context;
    }

    @Override
    public void initData() {
        redColor = getResources().getColor(R.color.buy_up_stroke);
        greenColor = getResources().getColor(R.color.buy_down_stroke);
        MinutesLineFragment minutesLineFragment = new MinutesLineFragment();
        KLineFragment kLineFragment = KLineFragment.newInstance(2);
        KLineFragment kLineFragment01 = KLineFragment.newInstance(3);
        KLineFragment kLineFragment02 = KLineFragment.newInstance(4);
        kLineFragment.setOnValueSelected(this);
        kLineFragment01.setOnValueSelected(this);
        kLineFragment02.setOnValueSelected(this);
        //添加页卡视图
        mViewList.add(minutesLineFragment);
        mViewList.add(kLineFragment);
        mViewList.add(kLineFragment01);
        mViewList.add(kLineFragment02);


        builder = new AlertDialog.Builder(mActivity);
        alertDialog = builder.setMessage("登录信息失效是否重新登录")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(mActivity, WebViewActivity.class);
                        intent.putExtra("mobile", (String) SPUtils.get(mActivity, "mobile", "18612620309"));
                        startActivity(intent);
                        dialog.dismiss();
                    }
                }).create();

        //添加页卡标题
        mTitleList.add("分时线");
        mTitleList.add("5分钟线");
        mTitleList.add("15分钟线");
        mTitleList.add("30分钟线");

        tabs.setTabMode(TabLayout.MODE_FIXED);//设置tab模式，当前为系统默认模式
        tabs.addTab(tabs.newTab().setText(mTitleList.get(0)));//添加tab选项卡
        tabs.addTab(tabs.newTab().setText(mTitleList.get(1)));
        tabs.addTab(tabs.newTab().setText(mTitleList.get(2)));
        tabs.addTab(tabs.newTab().setText(mTitleList.get(3)));
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        initHandlerHTTP();
                        break;
                    case 1:
                        if (!(wp_token.equals("空") && wp_token.equals(""))) {
                            initUser();
                        }
                        break;
                }
                return false;
            }
        });
        integerHashMap.setHandler(handler);
        initHandlerHTTP();

        MyPagerAdapter mAdapter = new MyPagerAdapter(getChildFragmentManager(), mViewList);
        vpView.setAdapter(mAdapter);//给ViewPager设置适配器
        tabs.setupWithViewPager(vpView);//将TabLayout和ViewPager关联起来。
    }

    private void initGetTodayKLine() {
        OkHttpUtils.get()
                .url(WPUrlBase.GET_TODAY_KLINE)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onResponse(String response, int id) {
//                        Log.e("InforMationFragment", response+"...");
                        try {
                            Gson gson = new Gson();
                            TodayKLineBean todayKLineBean = gson.fromJson(response, TodayKLineBean.class);
                            if (todayKLineBean.getCode().equals("200")) {
                                TodayKLineBean.XAG1Bean xag1 = todayKLineBean.getXAG1();
                                double high = xag1.getHIGH();
                                double low = xag1.getLOW();
                                double open = xag1.getOPEN();
                                double preclose = xag1.getPRECLOSE();
                                double[] klins = {high, low, open, preclose};
                                TextView[] textViews = {maxText, minText, todayText, afterText};

                                for (int i = 0; i < klins.length; i++) {
                                    if (klins[i] > preclose) {
                                        textViews[i].setTextColor(Color.rgb(245, 67, 55));
                                    } else if (klins[i] < preclose) {
                                        textViews[i].setTextColor(Color.rgb(19, 185, 77));
                                    }
                                }
                                afterText.setText((int) preclose + "");
                                maxText.setText((int) high + "");
                                minText.setText((int) low + "");
                                todayText.setText((int) open + "");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });

    }

    private void initHandlerHTTP() {
        OkHttpUtils.get()
                .url(WPUrlBase.Get_Now_Price)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        handler.sendEmptyMessageDelayed(0, 2000);
                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        Log.e("InforMationFragment", response);
                        if (InforMationFragment.this != null) {

                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String code = jsonObject.getString("code");
                                if (code.equals("200")) {
                                    JSONObject result = jsonObject.getJSONObject("result");
                                    String silver = result.getString("silver");

                                    if (isFirst) {
                                        isFirst = false;
                                        nowPrice.setText(silver);
                                    } else {
                                        if (!nowPrice.getText().equals("当前价格")) {
                                            int last = Integer.parseInt(nowPrice.getText().toString());
                                            int now = Integer.parseInt(silver);
                                            if (isBuy) {
                                                double yingkuizz = (now - buyPrice) * plRatio * count;
                                                java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
                                                if (buyDirection == 1) {
                                                    yingkuizz *= -1;
                                                } else if (buyDirection == 2) {
                                                    yingkuizz *= 1;
                                                }
                                                if (couponFlag == 1) {
                                                    if (yingkuizz <= 0) {
                                                        yingkuizz = 0;
                                                    }
                                                }
                                                if (yingkuizz < 0) {
                                                    yingkui.setTextColor(greenColor);
                                                } else if (yingkuizz > 0) {
                                                    yingkui.setTextColor(redColor);
                                                }
                                                String format = df.format(yingkuizz);
                                                yingkui.setText("" + format);
                                            } else {
                                                yingkui.setText("");
                                            }
                                            if (last < now) {
                                                nowPrice.setText(silver);
                                                nowPrice.setTextColor(Color.RED);
                                                Drawable drawable = mActivity.getResources().getDrawable(R.mipmap.shangzhang_icon);
                                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                                nowPrice.setCompoundDrawables(null, null, drawable, null);
                                            } else if (last > now) {
                                                nowPrice.setText(silver);
                                                nowPrice.setTextColor(Color.GREEN);
                                                Drawable drawable = mActivity.getResources().getDrawable(R.mipmap.xiadie_icon);
                                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                                nowPrice.setCompoundDrawables(null, null, drawable, null);
                                            }
                                        }
                                    }
                                    handler.sendEmptyMessageDelayed(0, 2000);
                                } else if (code.equals("1100")) {
                                    nowPrice.setText("休市时间");
                                    handler.sendEmptyMessageDelayed(0, 2000);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                handler.sendEmptyMessageDelayed(0, 2000);
                            } catch (IllegalStateException e) {
                                e.printStackTrace();
                                handler.sendEmptyMessageDelayed(0, 2000);
                            }
                        }

                    }
                });
        if (isEnd) {
            initGetTodayKLine();
        }
    }


    @Override
    public void initDestrory() {
        handler.removeMessages(0);
        OkHttpUtils.getInstance().cancelTag(this);//取消以this作为tag的请求
    }

    @Override
    public void onResume() {
        super.onResume();
        isLogin = (boolean) SPUtils.get(mActivity, "isLogin", false);
        wp_token = (String) SPUtils.get(mActivity, "wp_token", "空");

        if (isLogin) {
            loginLayout.setVisibility(View.GONE);
        } else {
            loginLayout.setVisibility(View.VISIBLE);
        }
        if (!wp_token.equals("空")) {
            initUser();
        } else if (isLogin) {
            tokenMiss();
        }
    }

    private void initUser() {
        JSONObject jsonWp_token = new JSONObject();
        try {
            jsonWp_token.put("token", wp_token);
            OkHttpUtils.get()
                    .url(WP_USER_BALANCES)
                    .addParams("p", jsonWp_token.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e("InforMationFragment", e.toString());
                        }

                        @Override
                        public void onResponse(String response, int id) {
//                            Log.e("InforMationFragment", response);
                            try {
                                JSONObject requry = new JSONObject(response);
                                String code = requry.getString("code");
                                if (code.equals("200")) {
                                    String result = requry.getString("result");
                                    myMoney.setText(result);
                                    buyLow.setEnabled(true);
                                    buyUp.setEnabled(true);
                                } else if (code.equals("1078")) {
                                    if (this != null) {

                                        tokenMiss();
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

            OkHttpUtils.get()
                    .addParams("p", jsonWp_token.toString())
                    .url(WP_USER_COUNTS)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            try {
                                JSONObject requry = new JSONObject(response);
                                String code = requry.getString("code");
                                if (code.equals("200")) {
                                    JSONArray result = requry.getJSONArray("result");
                                    addNum = 0;
                                    HashMap<Integer, Integer> numMap = new HashMap<Integer, Integer>();
                                    if (result != null && result.length() > 0) {
                                        for (int i = 0; i < result.length(); i++) {
                                            JSONObject NUM = result.getJSONObject(i);
                                            int num = NUM.getInt("NUM");
                                            int COUPONID = NUM.getInt("COUPONID");
                                            addNum += num;
                                            numMap.put(COUPONID, num);
                                        }
                                    }
                                    integerHashMap.setNumMap(numMap);
                                    myQuan.setText(addNum + "");
                                } else if (code.equals("1078")) {
                                    if (this != null) {

                                        tokenMiss();
                                    }
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

            OkHttpUtils.get()
                    .url(WP_USER_MYBUYLIST)
                    .addParams("p", jsonWp_token.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
//                            Log.e("InforMationFragment", response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (jsonObject.getString("code").equals("200")) {
                                    JSONArray result = jsonObject.getJSONArray("result");
                                    if (result != null && result.length() > 0) {
                                        isBuy = true;
                                        JSONObject jsonObject1 = result.getJSONObject(0);
                                        buyPrice = jsonObject1.getInt("buyPrice");// 购买价格
                                        plRatio = jsonObject1.getDouble("plRatio");// 浮动盈亏
                                        orderId = jsonObject1.getInt("orderId");// 订单ID
                                        double weightNum = jsonObject1.getDouble("weight");// 购买的重量
                                        double plAmount = jsonObject1.getDouble("plAmount");// 显示盈亏
                                        int productId = jsonObject1.getInt("productId");  //产品id
                                        int buyMoney = jsonObject1.getInt("buyMoney"); // 购买的钱数
                                        buyDirection = jsonObject1.getInt("buyDirection"); // 购买的方向
                                        couponFlag = jsonObject1.getInt("couponFlag"); // 是否用券
                                        count = jsonObject1.getInt("count"); // 买入手数
                                        String spec = jsonObject1.getString("spec");// 单位
                                        jiancang.setText(buyPrice + "");
                                        weight.setText(weightNum + spec);
                                        int fangxiang = 0;

                                        if (buyDirection == 1) {
                                            fangxiang = -1;
                                        } else if (buyDirection == 2) {
                                            fangxiang = 1;
                                        }
                                        double fee = 0;
                                        if (couponFlag == 0) {
                                            if (plAmount < 0) {
                                                yingkui.setTextColor(greenColor);
                                            } else if (plAmount > 0) {
                                                yingkui.setTextColor(redColor);
                                            }
                                            yingkui.setText(plAmount + "");

                                            if (productId == 4) {
                                                fee = 0.6 * count;
                                            } else if (productId == 10) {
                                                fee = 6 * count;
                                            } else if (productId == 11) {
                                                fee = 24 * count;
                                            }
                                        } else {
                                            if (plAmount <= 0) {
                                                plAmount = 0;
                                            }
                                            yingkui.setText(plAmount + "");

                                        }
                                        double yingkui = (fee) * fangxiang / (plRatio * count);
                                        double baobenjia = yingkui + buyPrice;
                                        java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
                                        baoben.setText(df.format(baobenjia));
                                        buyLayout.setVisibility(View.GONE);
                                        pingLayout.setVisibility(View.VISIBLE);
                                    } else {
                                        isBuy = false;
                                        buyLayout.setVisibility(View.VISIBLE);
                                        pingLayout.setVisibility(View.GONE);
                                        orderId = 0;
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * token 失效
     */
    private void tokenMiss() {
        if (!alertDialog.isShowing()) {
            alertDialog.show();
        }
        buyLow.setEnabled(false);
        buyUp.setEnabled(false);
    }

    @Override
    public void onPause() {
        super.onPause();
//        handler.removeMessages(0);
//        OkHttpUtils.getInstance().cancelTag(this);//取消以this作为tag的请求
    }

    @Override
    public void initView() {

    }

    @Override
    public View inflaterView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_information, null);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setOnValueSelected(float[] strings) {
        double high = strings[0];
        double low = strings[1];
        double open = strings[2];
        double preclose = strings[3];
        double[] klins = {high, low, open, preclose};
        TextView[] textViews = {maxText, minText, todayText, afterText};

        for (int i = 0; i < klins.length; i++) {
            if (klins[i] > preclose) {
                textViews[i].setTextColor(Color.rgb(245, 67, 55));
            } else if (klins[i] < preclose) {
                textViews[i].setTextColor(Color.rgb(19, 185, 77));
            }
        }

        afterText.setText((int) preclose + "");
        maxText.setText((int) high + "");
        minText.setText((int) low + "");
        todayText.setText((int) open + "");
    }

    @Override
    public void onTouch(boolean isEnd) {
        this.isEnd = isEnd;
    }


    @OnClick({R.id.buy_up, R.id.buy_low, R.id.ping_btn, R.id.login_btn, R.id.register_btn, R.id.login_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buy_up:
                BuyDialogFragment buyDialogFragmentUp = BuyDialogFragment.newInstance(BuyDialogFragment.BUY_UP, Double.parseDouble(myMoney.getText().toString()), integerHashMap, wp_token);
                buyDialogFragmentUp.show(getChildFragmentManager(), "");
                break;
            case R.id.buy_low:
                BuyDialogFragment buyDialogFragment = BuyDialogFragment.newInstance(BuyDialogFragment.BUY_DOWN, Double.parseDouble(myMoney.getText().toString()), integerHashMap, wp_token);
                buyDialogFragment.show(getChildFragmentManager(), "");
                break;
            case R.id.login_btn:
                Intent login = new Intent(mActivity, LoginActivity.class);
                startActivity(login);
                break;
            case R.id.register_btn:

                Intent register = new Intent(mActivity, RegisterActivity.class);
                startActivity(register);
                break;
            case R.id.login_layout:
                break;
            case R.id.ping_btn:
                initPing();
                break;
        }
    }

    private void initPing() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", wp_token);
            jsonObject.put("orderId", this.orderId);
            OkHttpUtils.get()
                    .url(WP_USER_CLOSEORDER)
                    .addParams("p", jsonObject.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
//                            Log.e("InforMationFragment", response);
                            try {
                                JSONObject jsonObject1 = new JSONObject(response);
                                String code = jsonObject1.getString("code");
                                if (code.equals("200")) {
                                    isBuy = false;
                                    handler.sendEmptyMessage(1);
                                    refreshMoney.clean();
                                    buyLayout.setVisibility(View.VISIBLE);
                                    pingLayout.setVisibility(View.GONE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    public interface RefreshMoney {
        void clean();
    }


    //ViewPager适配器
    class MyPagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> mViewList;

        public MyPagerAdapter(FragmentManager fm, List<Fragment> mViewList) {
            super(fm);
            this.mViewList = mViewList;
        }

        @Override
        public int getCount() {
            return mViewList.size();//页卡数
        }


        @Override
        public Fragment getItem(int position) {
            return mViewList.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position % mTitleList.size());
        }

    }

}
